/**
 * 小游戏管理
 */
class WeChatgGameManager {
	private _wx:any;
	private _sharedCanvas:any;
	//视频广告集合
	private video_ads = {};
	//当前视频广告id
    private current_video_ad_id = '';

	private _userInfoButton:any;

	public isShake:boolean;

	private shareTime:number;
	private isInshare:boolean;
	private curShareId:number;

	//一次分享可以失败的次数
	private shareFailTimes:number = 0;
	
	public constructor() {
		this._wx = window['wx'] || window['tt'];
		this._sharedCanvas = window["sharedCanvas"];
	}

	private static _instance:WeChatgGameManager;
	public static instance():WeChatgGameManager{
		if(!WeChatgGameManager._instance){
			WeChatgGameManager._instance = new WeChatgGameManager();
		}
		return WeChatgGameManager._instance;
	}

	public get wx()
	{
		return this._wx;
	}

	public login(){
		return platform.login();
	}

	public init()
	{
		this.isShake = true;
		this.isInshare = false;
		this.shareTime = 0;
		this.shareFailTimes = 0;
		this.onShow();
		this.onHide();
		this.onNetworkStatusChange();
		this.setKeepScreenOn();
		this.showShareMenu();
		RankManager.instance().loadFriendCloudStorage();	
	}

	//分享
	private showShareMenu()
	{
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				wx.showShareMenu();
			})
		}
	}

	public getOpenDataContext()
	{
		let wx = this._wx;
		if(wx)
		{
			return wx.getOpenDataContext();
		}
	}

	//微信展示loading 
	public showLoading(){
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				wx.showLoading({
					title:'数据载入中',
					mask:false,
					success:()=>{
					resolve();
					}
				});
			});
		}
	}

	/**
	 * 获取微信登录的一些数据（包含shareTicket的数据）
	 */
	public getOnShowData(){
		  //获取登录游戏的数据（包含shareTicket的数据）
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				return resolve(wx.getLaunchOptionsSync());
			});
		}
  	}

	//微信隐藏loading
	public hideLoading(){
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				wx.hideLoading({
					success:()=>{
						resolve();
					}
				});
			});
		}
	}

	/**
	 * 游戏进入前台
	 */
	private onShow(){
		let wx = this._wx;
		if(wx){
			wx.onShow((res) => {
				TTSoundManager.instance().goOnBgm();

				if(res && res['query'] && res['query']['from_openid'])
				{
					let queryData = {
						from_openid : res['query']['from_openid']
					}
					HttpManager.instance().sendPost(GameConst.httpUrl + 'warrioruser/handle_invite' , StringUtil.jsonToHttpPostString(queryData), (e)=>{
						
					})
				} 
				// if(res)
				// {
				// 	if(res['scene'] == (GameConst.wxScene.MainScene || GameConst.wxScene.DownScene))
				// 	{
				// 		//来自我的小程序
				// 		RoleCache.instance().isCanGetWxAward = true;
				// 	}
				// }
				// if(this.isInshare && !RoleCache.instance().reviewStatus)
				// {
				// 	let call:Function = function()
				// 	{
				// 		SharePrase.instance().requestOneAdvertisement({type:this.curShareId});
				// 	}
				// 	/**
				// 	 * 分享失败计数
				// 	 */
				// 	if(this.shareFailTimes <= 2 && Math.random() > 0.5)
				// 	{
				// 		this.shareFailTimes++;
				// 		// egret.setTimeout(()=>{
				// 			// MessageUtil.tips('请分享到不同的群~');
				// 		// },this, 500);
				// 		if(this.curShareId != ShareId.sign && this.curShareId != ShareId.invite && this.curShareId != ShareId.show_weapon)
				// 		this.showModal('系统提示','请分享到不同的群',true, '立即分享',call, this)
				// 		return;
				// 	}
				// 	this.isInshare = false;
				// 	let time = egret.getTimer() - this.shareTime;
				// 	if(time >= 2000)
				// 	{
				// 		this.shareFailTimes = 0;
				// 		// GameUtil.sendCntTOSever('share_num');
				// 		GameUtil.dispatchEvent(EventConst.SHARE_SUCCESS, {type:this.curShareId});
				// 	}
				// 	else
				// 	{
				// 		// egret.setTimeout(()=>{
				// 		// 	MessageUtil.tips('请分享到不同的群~');
				// 		// },this, 500);
				// 		if(this.curShareId != ShareId.sign && this.curShareId != ShareId.invite && this.curShareId != ShareId.show_weapon)
				// 		this.showModal('系统提示','请分享到不同的群',true, '立即分享',call, this)
				// 	}
				// 	this.curShareId = null;
				// 	this.shareTime = 0;
				// }
			})
		}
	}

	/**
	 * 展示微信弹框
	 */
	public showModal(title:string, content:string, showCancel:boolean, confirmText, call:Function, scope)
	{
		let wx = this._wx;
		if(wx)
		{
			wx.showModal({
				title: title, content: content, showCancel: showCancel, cancelText: "退出", confirmText:confirmText,
				success: (res) => {
					if (res.confirm) {
						if(call)
						call.call(scope);
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
					
				}
			})
		}
	}

	/**
	 * 游戏进入后台
	 */
	private onHide(){
		let wx = this._wx;
		if(wx){
			wx.onHide((res) => {
				TTSoundManager.instance().stopBgm();
				if(!this.isInshare)
				LoginPrase.instance().LogOut();
			})
		}
	}

	private _userInfo:any = {};
	public get userInfo(){
		return this._userInfo;
	}

	//设置屏幕常亮
	private setKeepScreenOn(){
		let wx = this._wx;
		if(!wx) return;
		return new Promise((resolve, reject) => {
			wx.setKeepScreenOn({
				keepScreenOn:true,
				success:()=>{
				resolve();
				}
			});
		});
	}

	/**
	 * 15ms震动
	 */
	public vibrateShort(){
		if(this.isShake)
		{
			let wx = WeChatgGameManager.instance()._wx;
			if(wx){
				wx.vibrateShort();
			}
		}
	}	

	public judgeIsIphoneX(){
		let wx = WeChatgGameManager.instance()._wx;
		if(wx){
			let res = wx.getSystemInfoSync();
			if(res)
			{
				let modelmes = res.model;
				if (modelmes.search('iPhone X') != -1 || modelmes.search('iPhone XS') != -1) {
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		return false;
	}

	public getUserInfo(call?:Function, scope?:any){
		// if(!this._userInfo){
			LogUtil.log('尝试拉取用户数据');
			platform.getUserInfo().then((e)=>{
				LogUtil.log('获得用户数据');
				this._userInfo = e;
				if(call){
					call.call(scope, e);
				}
			}).catch((e)=>{
				LogUtil.log('拉取用户数据失败');
				// MessageUtil.tips('在小程序设置中更改授权状态再来试一试~');
				this.showModal('提示','在小程序设置中更改授权状态再来试一试~',true,'去修改',null,null);
				// this.showUserInfoButton(call, scope);
			});
		// }
	}

	public showUserInfoButton(call?:Function, scope?:any){
		// if(this._userInfoButton || !this._wx){
		// 	return;
		// }
		// let data = this._wx.getSystemInfoSync();
		// let windowWidth = data.windowWidth;
		// let windowHeight = data.windowHeight;
		// let scale = windowHeight/1280;
		// let scale1 = windowWidth / 720;
		// LogUtil.log('显示授权按钮')
		// let w = 212 * scale;
		// let h = 69 * scale;
		// this._userInfoButton = this._wx.createUserInfoButton({
		// 	type: 'image',
		// 	// text: '获取用户信息'
		// 	image:'resource/assets/alert/btn_sure.png',
		// 	style: {
		// 		left:windowWidth-w>>1,
		// 		top: 672 * scale1,
		// 		width: w,
		// 		height: h
		// 	}
		// })
		// this._userInfoButton.onTap((e) => {
		// 	if(e.errMsg == 'getUserInfo:ok'){
		// 		LogUtil.log('授权按钮成功回调');
		// 		this._userInfo = e.userInfo;
		// 		if(call){
		// 			call.call(scope, e);
		// 		}
		// 	}
		// })
	}

	public showUserInfoButton1(call?:Function, scope?:any){
		// if(this._userInfoButton || !this._wx){
		// 	return;
		// }
		// let data = this._wx.getSystemInfoSync();
		// let windowWidth = data.windowWidth;
		// let windowHeight = data.windowHeight;
		// let scale = windowHeight/1280;
		// let scale1 = windowWidth / 720;
		// LogUtil.log('显示授权按钮')
		// let w = 212 * scale;
		// let h = 69 * scale;
		// this._userInfoButton = this._wx.createUserInfoButton({
		// 	type: 'image',
		// 	// text: '获取用户信息'
		// 	image:'resource/assets/weChat/userInfoButton.png',
		// 	style: {
		// 		left:windowWidth-w>>1,
		// 		top: 800 * scale1,
		// 		width: w,
		// 		height: h
		// 	}
		// })
		// this._userInfoButton.onTap((e) => {
		// 	if(e.errMsg == 'getUserInfo:ok'){
		// 		LogUtil.log('授权按钮成功回调');
		// 		this._userInfo = e.userInfo;
		// 		if(call){
		// 			call.call(scope, e);
		// 		}
		// 	}
		// })
	}

	public hideUserInfoButton(){
		if(this._userInfoButton){
			LogUtil.log('关闭授权按钮')
			this._userInfoButton.hide();
			this._userInfoButton.destroy();
			this._userInfoButton = null;
		}
	}

	/**
	 * 创建排行榜显示对象
	 */
	public createRankListDisplayObject(){
		let open = platform['openDataContext'];
		if(open){
			return open.createDisplayObject(null, GlobalManager.instance().curWidth(), GlobalManager.instance().curHeight());
		}
	}

	/**
	 * 创建即将超越好友的对象
	 */
	public createBeyondDisplayObject(){
		let open = platform['openDataContext'];
		if(open){
			return open.createDisplayObject(null, 100, 160);
		}
	}

	/**
	 * 向开放数据域发送数据
	 * @param data {ket:value}
	 */
	public sendMessageToOpen(data:any){
		let open = platform['openDataContext'];
		if(open){
			open.postMessage(data);
		}
	}

	/**	
	 * 设置用户数据到微信后台，注意：不设置数据则无法通过getFriendCloudStorage获取用户数据
	 * @param data:json
	 */
	public setUserDataToCould(data:any[]){
		let open = platform['openDataContext'];
		if(open){
			open.setUserDataToCould(data);
		}
	}

	/**
	 * 播放视频广告
	 * param：
	 * 		ad_id:string 广告id
	 * 		Error_call:Function  发生错误或者观看失败的回调
	 * 		Success_call:Function 完整观看视频的回调函数
	 */
	public showVideoAd(ad_id:string, Success_call?:Function,Error_call?:Function, scope?)
	{	let wx = this._wx;
		if(wx)
		{
			let SDKVersion = wx.getSystemInfoSync().SDKVersion;
			// 无ad_id时弹出警告
			if (!(ad_id)) {
				wx.showModal({
					title: '系统提示', content: "请填入视频id", showCancel: false, cancelText: "", confirmText: "确定",
					success: () => {
						if(Error_call)
						Error_call.call(scope);
					}
				})
				return;
			}

			// 低版本兼容方法
			if (!(typeof(wx.createRewardedVideoAd) == 'function') || GameUtil.compareVersion(SDKVersion, GameConst.videoAd_version) == -1) {
				wx.showModal({
					title: '系统提示', content: "微信版本较低，暂不支持", showCancel: false, cancelText: "", confirmText: "确定",
					success: () => {
						if(Error_call)
						Error_call.call(scope);
						MessageUtil.tips("观看视频失败");
					}
				})
				return;
			}

			this.video_ads[ad_id] = wx.createRewardedVideoAd({
				adUnitId: ad_id
			})
			this.current_video_ad_id = ad_id;
			let isPlaySound = false;

			//加载广告视频
			this.video_ads[ad_id].load()
            .then(() => {
				// 播放广告时暂停背景音乐
				if(TTSoundManager.instance().isBGMPlay)
				{
					TTSoundManager.instance().swBGM();
					TTSoundManager.instance().swAudio();
					isPlaySound = true;
				}
                // 加载成功后播放视频
                this.video_ads[ad_id].show();
				GameManager.instance.addTodayVedioTimes();
            })
            // 加载失败时直接当作玩家视频广告观看成功
            .catch(err => {
				wx.showModal({
                    title: '系统提示', content: "已经到达看视频的上限了哦！", showCancel: false, cancelText: "", confirmText: "确定",
                    success: () => {
                        if(Error_call)
						{
							Error_call.call(scope);
							this.current_video_ad_id = '';
						}
                    }
                })
            });

			this.video_ads[ad_id].onError(err => {
				console.log(err);
			});

			// 兼容新老版本广告关闭按钮
			this.video_ads[ad_id].onClose(res=> {
				if (res && res.isEnded || res === undefined) {
					// 用户完整观看广告
					LogUtil.log("回调成功");
					if(Success_call)
					{
						Success_call.call(scope);
						this.current_video_ad_id = '';
					}
				} else {
					// 用户提前点击了【关闭广告】按钮,进入失败回调
					LogUtil.log("回调失败");
					if(Error_call)
						Error_call.call(scope);
					this.current_video_ad_id = '';
				}
				// 关闭后重开背景音乐
				if(isPlaySound)
				{
					TTSoundManager.instance().swAudio();
					TTSoundManager.instance().swBGM();
				}
				// 停止监听close方法
				this.video_ads[ad_id].offClose(res);
			})
		}
	}

	/**
	 * 插入banner广告
	 */
	 public showBannerAd(ad_id: string): any {
		let wx = this._wx;
		if(wx)
		{
			let SDKVersion = wx.getSystemInfoSync().SDKVersion;
			// 无ad_id时弹出警告
			if (!(ad_id)) {
				wx.showModal({
					title: '系统提示', content: "请填入广告id", showCancel: false, cancelText: "", confirmText: "确定",
					success: () => {}
				})
				return null;
			}
			// 低版本兼容方法
			let bannerAd = (GameUtil.compareVersion(SDKVersion, GameConst.videoAd_version) != -1) ? wx.createBannerAd({
				adUnitId: ad_id,
				style: {
					left: 0,
					top: 0,
					width: 350
				}
			}) : null;
			if (bannerAd) {
				bannerAd.onError(err => {
					console.log(err);
				});
				// bannerAd.show();
				let { screenWidth, screenHeight } = wx.getSystemInfoSync()
				bannerAd.onResize(res => {
					// banner广告放在底部
					bannerAd.style.top = screenHeight - bannerAd.style.realHeight;
					bannerAd.style.left = screenWidth - bannerAd.style.realWidth >> 1;
				});
				
				// bannerAd.style.width = screenWidth;
				// bannerAd.onLoad(() => {
				// 	bannerAd.show();
				// })
			}
			return bannerAd;
		}
    }

	/**
	 * 游戏网络处理
	 */
	public onNetworkStatusChange(){
		let wx = this._wx;
		if(wx){
			wx.onNetworkStatusChange((res) => {
				if(!res.isConnected)
				{
					//网络连接异常
					MessageUtil.tips('网络异常！！')
				}
				else
				{
					//网络连接正常
				}
			})
		}
	}

	/**
	 * 设置分享数据
	 */
	public setShareData(data:Object){
		return platform.setShareData(data);
	}

	/**
	 * 分享
	 * 使用分享功能请调用 SharePrase.instance().requestOneAdvertisement({type:类型});
	 */
	public share(data?:any){
		let title = '切个棒棒锤';
		let imageUrl = "resource/assets/weChat/share/normalShare.png";
		if(data)
		{
			//容错处理
			if(data["title"])
				title = data["title"];
			if(data["imgUrl"])
				imageUrl = data["imgUrl"]
		}
		let prama = data['prama'];
		
		let query = {};
		if(ShareId.invite == prama.type)
		{
			//分享必要参数
			query = {
				from_openid:RoleCache.instance().openid
			}
		}
		else if(ShareId.show == prama.type)
		{
			//炫耀分享需要展示分数
			title = prama.title
		}
		
		this.setShareData({
			title:title,
			imageUrl:imageUrl,
			query: StringUtil.jsonToHttpPostString(query)
		});
		platform.share();
		egret.setTimeout(()=>{
			GameUtil.dispatchEvent(EventConst.SHARE_SUCCESS, {type:prama.type});
		}, this, 3e3)
		// if(!RoleCache.instance().reviewStatus)
		// {
		// 	this.isInshare = true;
		// 	this.shareTime = egret.getTimer();
		// 	this.curShareId = prama.type;
		// }
	}

	//跳转
	public navigateToMiniProgram(appid?)
	{
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				let data = {
					appId: appid,
					success(res) {
						// 打开成功
					},
					cancel(res) {
						
					}
				}
				wx.navigateToMiniProgram(data);
			})
		}
	}

	//阿拉丁自定义事件
	public sendALDEvent(eventName:string, key:string, value:string)
	{
		// let wx = this._wx;
		// if(wx)
		// {
		// 	wx.aldSendEvent(eventName,{key : value});
		// }
	}

	//检验tocken是否过期
	public checkSession(Success_call:Function, scope)
	{
		let wx = this._wx;
		if(wx)
		{
			wx.checkSession({
				success() {
					// session_key 未过期，并且在本生命周期一直有效
					Success_call.call(scope);
				},
				fail() {
					// wx.login() // 重新登录
					WeChatgGameManager.instance().Login();
				}
			})
		}
	}

	//设置本地storage
	public setStorage(data:any, Success_call:Function)
	{
		let wx = this._wx;
		if(wx)
		{
			wx.setStorage({
				key: data.key,
				data: data.value,
				success (res){
					if(Success_call)
					Success_call();
				}
			})
		}
	}

	//从本地缓存中拿取数据
	public getStorage(key:string, Success_call:Function, Fail_call:Function, scope)
	{
		let wx = this._wx;
		if(wx)
		{
			try {
				const value = wx.getStorageSync(key);
				if (value) {
					HttpManager.instance().token = value;
					Success_call.call(scope, value);
				}
				else
				{
					Fail_call.call(scope);
				}
			} 
			catch (e) {
				LogUtil.error(e);		
			}
		}
	}

	//本地拿取数据2
	public getStorge2(key:string)
	{
		let wx = this._wx;
		if(wx)
		{
			try {
				const value = wx.getStorageSync(key)
				if (value) {
					return value;
				}
				else
				{
					return 0;
				}
			} 
			catch (e) {
				LogUtil.error(e);	
			}
		}
	}

	//微信登录
	public Login()
	{
		WeChatgGameManager.instance().login().then((e)=>{
			if(e && e.code)
			{
				HttpManager.instance().sendPost(GameConst.httpUrl + 'warrioruser/login', 'code=' + e.code + '&anonymous_code=' + e.anonymousCode, (e)=>{
					let data = JSON.parse(e);
					if(data && data.data)
					{
						let token = data.data.token
						let key_da = {
							key:'fruit_token',
							value:token
						}
						WeChatgGameManager.instance().setStorage(key_da,()=>{
							HttpManager.instance().token = key_da.value;
							LoginPrase.instance().Login();
						});
					}
				}, this);
			}
			else
			{
				LogUtil.error('login fail');
			}
		});
	}

	//**播放一首音乐 */

}